package com.h2cloud.JUCTest.patten;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Package: com.h2cloud.JUCTest.patten
 * @ClassName: TestOrder2
 * @Author: wulongkai
 * @CreateTime: 2024/3/13 16:08
 * @Description:
 */
class SyncNotify {
	int count = 1;

	public void print(int flag) throws Exception {
		while (count <= 100) {
			synchronized (this) {
				while (count % 3 != flag) {
					this.wait();
				}
				if (count > 100) {
					return;
				}
				System.out.println(Thread.currentThread().getName() + ": " + count);
				count++;
				this.notifyAll();
			}
		}
	}
}

class Reentrant {
	ReentrantLock lock = new ReentrantLock();
	Condition waitSet = lock.newCondition();
	int count = 1;
	public void print(int flag) throws Exception {
		while (count <= 100) {
			lock.lock();
			try {
				while (count % 3 != flag) {
					waitSet.await();
				}
				if (count > 100) {
					return;
				}
				System.out.println(Thread.currentThread().getName() + ": " + count);
				count++;
				waitSet.signalAll();
			} finally {
				lock.unlock();
			}
		}
	}
}

public class TestOrder2 {
	public static void main(String[] args) throws InterruptedException {
		Reentrant reentrant = new Reentrant();
		new Thread(() -> {
			try {
				reentrant.print(0);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}, "t1").start();

		Thread.sleep(1000);
		new Thread(() -> {
			try {
				reentrant.print(1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}, "t2").start();

		new Thread(() -> {
			try {
				reentrant.print(2);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}, "t3").start();
	}
}

